#!/bin/bash
# script name: 磁盘增幅监测脚本
# author: subushi
# update date: 2025.07.30


# 1. 定义变量
DATA_DIR="/data"   # 需要监测的磁盘
LOG_FILE="/opt/pre_monitor/disk/disk_usage_history.log"   # 监测输出的记录
DATETIME=$(date +"%Y-%m-%d %H:%M")
HEADER="日期                | 已用空间     | 剩余空间     | 使用率  | 日增幅  | 增幅百分比"
DISK_LABEL="                                   【${DATA_DIR}】"

# 2. 确保日志目录存在
mkdir -p "$(dirname "$LOG_FILE")"

# 3. 初始化日志文件（处理表头和标识）
if [ ! -f "$LOG_FILE" ]; then
    echo "$DISK_LABEL" > "$LOG_FILE"
    echo "$HEADER" >> "$LOG_FILE"
elif ! grep -qxF "$HEADER" "$LOG_FILE"; then
    # 若表头格式变化，覆盖旧表头（避免历史格式冲突）
    sed -i "2c $HEADER" "$LOG_FILE"  # 将第2行替换为新表头
fi

# 4. 获取磁盘当前数据（核心：确保数值正确）
USED_GB_RAW=$(df -BG "$DATA_DIR" 2>/dev/null | awk 'NR==2 {gsub(/G/,""); printf "%.2f", $3}')
if [ -z "$USED_GB_RAW" ]; then
    echo "❌ 错误：无法获取磁盘数据，请检查 $DATA_DIR 是否存在"
    exit 1
fi
USED_WITH_UNIT="${USED_GB_RAW}GB"

# 剩余空间（GB，带单位）
AVAIL_GB=$(df -BG "$DATA_DIR" 2>/dev/null | awk 'NR==2 {gsub(/G/,""); printf "%.2f", $4}')
AVAIL_WITH_UNIT="${AVAIL_GB}GB"

# 使用率（%，带单位）
USAGE_PERCENT=$(df -h "$DATA_DIR" 2>/dev/null | awk 'NR==2 {gsub(/%/,""); print $5}')
USAGE_WITH_UNIT="${USAGE_PERCENT}%"

# 5. 计算日增幅（处理历史数据为空的情况）
PREVIOUS_USED_GB=$(tail -n +3 "$LOG_FILE" 2>/dev/null | tail -n 1 | awk -F '|' '{gsub(/GB| /,""); print $2}')
# 若PREVIOUS_USED_GB为空（如首次执行或日志格式错误），设为0
if [ -z "$PREVIOUS_USED_GB" ] || ! [[ "$PREVIOUS_USED_GB" =~ ^[0-9.]+$ ]]; then
    PREVIOUS_USED_GB=0
fi

# 计算增幅（用bc前先检查数值合法性）
if [ $(echo "$PREVIOUS_USED_GB == 0" | bc 2>/dev/null) -eq 1 ]; then
    GROWTH_GB="--"
    GROWTH_PERCENT="--"
else
    # 确保USED_GB_RAW和PREVIOUS_USED_GB是数字
    if [[ "$USED_GB_RAW" =~ ^[0-9.]+$ ]] && [[ "$PREVIOUS_USED_GB" =~ ^[0-9.]+$ ]]; then
        GROWTH_RAW=$(echo "scale=2; $USED_GB_RAW - $PREVIOUS_USED_GB" | bc 2>/dev/null)
        GROWTH_GB="${GROWTH_RAW}GB"
        GROWTH_PERCENT=$(echo "scale=2; ($GROWTH_RAW / $PREVIOUS_USED_GB) * 100" | bc 2>/dev/null)
        GROWTH_PERCENT="${GROWTH_PERCENT}%"
    else
        GROWTH_GB="ERROR"
        GROWTH_PERCENT="ERROR"
    fi
fi

# 6. 写入数据行
printf "%-20s| %-12s | %-12s | %-7s | %-7s | %s\n" \
    "$DATETIME" \
    "$USED_WITH_UNIT" \
    "$AVAIL_WITH_UNIT" \
    "$USAGE_WITH_UNIT" \
    "$GROWTH_GB" \
    "$GROWTH_PERCENT" >> "$LOG_FILE"

# 7. 输出执行结果
echo "✅ 磁盘监控：$DATETIME - 已用: $USED_WITH_UNIT, 增幅: $GROWTH_GB ($GROWTH_PERCENT)"